﻿using System;
using System.Collections.Generic;
using Microsoft.Samples.ServiceHosting.StorageClient;
using WASM.WebSite.DataEntities;

namespace WASM.WebSite.Models
{
	public class QueueRepository
	{
		QueueStorage _queueStorage = null;

		public QueueRepository(string storageUri, string accountName, string key)
		{
			_queueStorage = QueueStorage.Create(new Uri(storageUri), null, accountName, key);
		}

		public static QueueRepository Create(Guid azureStorageId)
		{
			AzureStorage azureStorage = AzureStorageUserSettingsRepository.Single(azureStorageId);
			return new QueueRepository(azureStorage.asUrl, azureStorage.asAccountName, azureStorage.asKey);
		}

		public IEnumerable<MessageQueue> QueueList()
		{
			return _queueStorage.ListQueues();
		}

		public void QueueCreate(string queueName)
		{
			GetMessageQueue(queueName).CreateQueue();
		}

		public void QueueDelete(string queueName)
		{
			GetMessageQueue(queueName).DeleteQueue();
		}

		public bool IsQueueExist(string queueName)
		{
			return GetMessageQueue(queueName).DoesQueueExist();
		}

		public IEnumerable<Message> MessageList(string queueName)
		{
			return GetMessageQueue(queueName).PeekMessages(32);
		}

		public void MessageCreate(string queueName, string messageContent)
		{
			GetMessageQueue(queueName).PutMessage(new Message(messageContent));
		}

		public void MessageDeleteTop(string queueName)
		{
			MessageQueue messageQueue = GetMessageQueue(queueName);
			Message message = messageQueue.GetMessage();
			messageQueue.DeleteMessage(message);
		}

		private MessageQueue GetMessageQueue(string queueName)
		{
			return _queueStorage.GetQueue(queueName);
		}
	}
}